﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Riba.MVVMSL
{
	/// <summary>
	/// 
	/// </summary>
	public class ViewEventHandlerControl : Control
	{
		/// <summary>
		/// 
		/// </summary>
		public ViewEventHandlerControl()
		{
			DefaultStyleKey = typeof(ViewEventHandlerControl);
		}

		/// <summary>
		/// 
		/// </summary>
		public sealed override void OnApplyTemplate()
		{
			base.OnApplyTemplate();

			if (DataContext == null || DesignerProperties.IsInDesignTool)
				return;

			var view = GetRoot(this) as FrameworkElement;

			ViewEventHandler.HandleViewModelBaseEvents(view, DataContext as ViewModelBase);
		}

		private static DependencyObject GetRoot(DependencyObject o)
		{
			var p = VisualTreeHelper.GetParent(o);
			
			if (p == null)
				return o;

			return GetRoot(p);
		}
	}
}
